package com.briup.client;

import com.briup.Configuration;
import com.briup.client.Client;
import com.briup.entity.Environment;
import com.briup.support.ConfigurationAware;
import com.briup.support.PropertiesAware;
import com.briup.util.Log;
import com.briup.util.LogImpl;

import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Collection;
import java.util.Properties;

/**
 * 网络模块的客户端
 */
public class ClientImpl implements Client, PropertiesAware,ConfigurationAware {
    private String host;
    private int port;
    private Log log;

    @Override
    /**
     * 使用网络编程   客户端发送数据
     * @param collection 要发送的数据 采集模块采集的数据
     */
    public void send(Collection<Environment> collection) throws Exception {
        //创建客户端   传入 服务器地址以及端口号
        Socket socket = new Socket(host, port);
        log.info("客户端创建成功 连接到服务器。。。。");
        //获取网络的输出流
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        //输出对象
        oos.writeObject(collection);
        //刷新
        oos.flush();
        //关闭资源
        oos.close();
        log.info("客户端发送数据完毕  即将关闭");
        socket.close();
    }

    @Override
    public void init(Properties properties) throws Exception {
        host = properties.getProperty("host");
        port = Integer.parseInt(properties.getProperty("port"));
    }


    @Override
    public void setConfiguration(Configuration configuration) throws Exception {
      log=  configuration.getLogger();
    }
}
